<?php
namespace Home\Controller;
use Think\Controller;
	class ProductController extends InitializeController{
		public function index(){
          $db = M('Product');
    			$this->top = M('Menu')->where('top=1')->select();
	        $count = $db->count();// 查询满足要求的总记录数

	        if (I('id') == 0) {
		        //商城主页显示最近6条商品
		        $pages = $db->limit('0,6')->order('id DESC')->select();
	        }else{
	       		$Page = new \Extend\Page($count,6);// 实例化分页类 传入总记录数和每页显示的记录数(25)
	        	$pages = $db->limit($Page->firstRow.','.$Page->listRows)->where("mid=%d",I('id'))->order('id asc')->select();
	        }

	        //取最新4条
	        $this->newest = $db->where("mid=%d",I('id'))->order('id DESC')->limit(0,4)->select();
	        $this->assign('model', $pages);
	        $this->assign('page',$show);
			$this->display();
		}



		public function car(){
            header("Content-Type:text/html;charset=utf-8");
            //用关联模型 多对多?
			$User = D('User');
			$user_id = $_SESSION['mallUserId'];
			//用户vs商品more_to_more
			$user_to_prod = $User->relation(true)->where("user_id=%d",array($user_id))->find();
			//查询该用户所购买的商品!
	        // test($user_to_prod['user_to_prod']);
			$count = count($user_to_prod);// 查询满足要求的总记录数
	        $Page = new \Extend\Page($count,3);
	        // 实例化分页类 传入总记录数和每页显示的记录数(3)
	        $show = $Page->show();// 分页显示输出
	        $i = 0;

	        $judgeJump = 0;


	        //单独查一次count,未尝试优化
	        foreach ($user_to_prod['user_to_prod'] as $v) {
	        	$cou = M('prod_user')->where("user_id=%d and pid=%d",array($user_id,$v['id']))->select();


	        	if ($judgeJump>0 && count($cou)>1) {
	        		$judgeJump --;
	        		continue;
	        	}


	        	if (count($cou)>1) {
	        		foreach ($cou as $k=>$v) {
		        		$user_to_prod['user_to_prod']["$i"]['count'] = $cou["$k"]['count'];
			        	$user_to_prod['user_to_prod']["$i"]['unit'] = $cou["$k"]['price'];
			        	$user_to_prod['user_to_prod']["$i"]['content'] = $cou["$k"]['content'];
			        	$user_to_prod['user_to_prod']["$i"]['color'] = $cou["$k"]['color'];
			        	$user_to_prod['user_to_prod']["$i"]['price'] = (int)$cou["$k"]['price']*(int)$cou["$k"]['count'];
			        	$user_to_prod['user_to_prod']["$i"]['oldId'] = $cou["$k"]['id'];

			        	// $user_to_prod['user_to_prod']["$i"]['checkout'] = $cou["$user_id"]['checkout'];
			        	$allPrice += $user_to_prod['user_to_prod']["$i"]['price'];
		        		$i++;
		        	}
		        	$judgeJump = count($cou);
		        	continue;
	        	}else{
	        		$user_to_prod['user_to_prod']["$i"]['count'] = $cou['0']['count'];
		        	$user_to_prod['user_to_prod']["$i"]['unit'] = $cou['0']['price'];
		        	// $user_to_prod['user_to_prod']["$i"]['checkout'] = $cou["$user_id"]['checkout'];
		        	$user_to_prod['user_to_prod']["$i"]['content'] = $cou['0']['content'];
		        	$user_to_prod['user_to_prod']["$i"]['color'] = $cou['0']['color'];
		        	$user_to_prod['user_to_prod']["$i"]['price'] = (int)$cou['0']['price']*(int)$cou['0']['count'];
		        	$user_to_prod['user_to_prod']["$i"]['oldId'] = $cou['0']['id'];


		        	$allPrice += $user_to_prod['user_to_prod']["$i"]['price'];
	        		$i++;
	        	}

	        	// test($cou);

	        	//价格为总价 不是单价
	        	// $i++;
	        }
            $recommend = D('Recommend');
            $recd = $recommend->getRecommend();
            $rand = $recommend->numberRand(0,15,10);
            //推荐五件商品
            unset($recommend);
            foreach ($rand as $k => $v){
                $recommend[] = $recd[$v];
                $recommend[$k]['id'] += $v+1;
            }
	        // test($user_to_prod['user_to_prod']);
	        $this->assign('model',$user_to_prod['user_to_prod']);
	        // test($user_to_prod['user_to_prod']);
	        $this->assign('allPrice',$allPrice);
	        $this->assign('page',$show);
	        $this->assign('recommend', $recommend);
			$this->display();
		}

		public function add_car(){
			if ($_GET['action'] == 'ajax') {
				$db = M('prod_user');


				$where = array(
					'pid'=> I('id'),
					'user_id' => $_SESSION['mallUserId'],
					'price' => I('price'),
					'content' => I('content'),
					'color' => I('color'),
 					);
				if ($judge = $db ->where($where)->select()) {
					if ($add = $db->where($where)->setInc('count',I('count'))) {

						$count = $db->where('user_id=%d',$_SESSION['mallUserId'])->field('count')->select();
						for ($i=0; $i <count($count) ; $i++) {
							$carCount += $count["$i"]['count'];
						}

						$arr['success']=1;
						$arr['count'] = 1;
						$arr['carCount'] = $carCount;
						echo json_encode($arr);	//将数值转换成json数据存储格式
					}
				}else{
					if ($_SESSION['mallUserId'] == NULL) {
						$arr['success']=0;
						echo json_encode($arr);	//将数值转换成json数据存储格式
					}else{
						$data = array(
							'user_id' => $_SESSION['mallUserId'], //后期改掉!
							'pid' => I('id'),
							'count' => 1,
							'price' => I('price'),
							'content' => I('content'),
							'color' => I('color')
						);
						if ($add = $db->data($data)->add()) {

							$count = $db->where('user_id=%d',$_SESSION['mallUserId'])->field('count')->select();
							for ($i=0; $i <count($count) ; $i++) {
								$carCount += $count["$i"]['count'];
							}

							$arr['success']=1;
							$arr['count'] = 1;
							$arr['carCount'] = $carCount;
							// $arr['carCount'] = $this->carCount();
							echo json_encode($arr);	//将数值转换成json数据存储格式
						}
					}

				}

			}
		}

		public function changeCar(){
			if ($_GET['action'] == 'ajax') {
				$db = M('prod_user');
				$where['pid'] = I('id');
				$where['user_id'] = $_SESSION['mallUserId'];
				//此处数组做条件 依然不好使
				if ($judge = $db ->where($where)->setField(array('price','count'),array(I('price')*I('count')))) {
					$arr['success']=1;
					echo json_encode($arr);	//将数值转换成json数据存储格式
				}
			}
		}

		public function  checkout(){
			//此处结算为ajax,后期不行就改成表单提交
			$db = M('prod_user');
			$prod_user = $db->where("user_id=%d",$_SESSION['mallUserId'])->select();
			$checkout = M('checkout')->select();
			foreach ($prod_user as $k => $v) {
				$prod_user["$k"]['time'] = date("Y-m-d H:i:s",time());
				//run_,date将时间戳转换格式输出
				foreach ($checkout as $cv) {
					if ($v['user_id'] == $cv['user_id']&&$v['pid']==$cv['pid']) {
						$judge["$k"]=M('checkout')->where("user_id=%d and pid=%d",array($_SESSION['mallUserId'],$v['pid']))->setInc('count',$v['count']);
					}
				}
				if (!isset($judge["$k"])) {
					$judge["$k"] = M('Checkout')->data($prod_user["$k"])->add();
				}
			}
			foreach ($judge as $v) {
				if (!$v) {
					$arr['success'] = 0;
					echo json_encode($arr);	//将数值转换成json数据存储格式
				}
			}

			if ($judge =$db->where("user_id=%d",$_SESSION['mallUserId'])->delete()) {
				$arr['success']=1;
				$arr['allPrice'] = I('allPrice');
				echo json_encode($arr);	//将数值转换成json数据存储格式
			}
		}

		public function ajaxChange(){
			$db = M('prod_user');
			$price = $db->where("id=%d",I('oldId'))->field('price')->select();
			if (I('get.action') == 'ajax') {
				if ($judge = $db->where("id=%d and user_id=%d",array(I('oldId'),$_SESSION['mallUserId']))->setField('count',I('num'))) {

					$allPro = $db->where('user_id=%d',$_SESSION['mallUserId'])->select();
					foreach ($allPro as $v) {
						$cou[] = $v['count'];
						$pri[] = $v['price'];
					}
					for ($i=0; $i <count($cou) ; $i++) {
						$allPrice += $cou["$i"]*$pri["$i"];
					}

					$response = array(
						'total' => $price['0']['price']*I('num'),
						'newNum' => I('num'),
						'allPrice' => $allPrice,
						'errno'  =>  '0',
						'errmsg' =>  'success',
						'data'   =>  true,
					);
					$this->ajaxReturn($response);
					// echo json_encode($response);
				}
			}

		}

		public function carDelete(){
			$db = M('prod_user');
			if ($judge = $db->where("user_id=%d and pid=%d",$_SESSION['mallUserId'],I('get.id'))->delete()) {
				header("Location: ".U('Product/car'));
			}
		}

		// public function calculate(){
		// 	//用关联模型 多对多?
		// 	$User = D('User');
		// 	$user_id = $_SESSION['mallUserId'];
		// 	//用户vs商品more_to_more
		// 	$user_to_prod = $User->relation(true)->where("user_id=%d",array($user_id))->find();
		// 	//查询该用户所购买的商品!
	 //        // test($user_to_prod['user_to_prod']);
		// 	$count = count($user_to_prod);// 查询满足要求的总记录数
	 //        $Page = new \Extend\Page($count,3);
	 //        // 实例化分页类 传入总记录数和每页显示的记录数(3)
	 //        $show = $Page->show();// 分页显示输出
	 //        //单独查一次count,未尝试优化
	 //        foreach ($user_to_prod['user_to_prod'] as $k=>$v) {
	 //        	$cou = M('prod_user')->where("user_id=%d and pid=%d",array($user_id,$v['id']))->field('count')->select();

	 //        	// test($cou);
	 //        	$user_to_prod['user_to_prod']["$k"]['count'] = $cou['0']['count'];
	 //        	$user_to_prod['user_to_prod']["$k"]['price'] *=$cou['0']['count'];
	 //        	// $user_to_prod['user_to_prod']["$k"]['checkout'] = $cou["$user_id"]['checkout'];
	 //        	$allPrice += $user_to_prod['user_to_prod']["$k"]['price'];
	 //        	//价格为总价 不是单价
	 //        }
	 //        // test($user_to_prod['user_to_prod']);
	 //        $this->assign('model',$user_to_prod['user_to_prod']);
	 //        $this->assign('allPrice',$allPrice);
	 //        $this->assign('page',$show);
		// 	$this->display();
		// }

		public function getCarInfo()
		{
            header("Content-Type:text/html;charset=utf-8");
            //用关联模型 多对多?
            $User = D('User');
            $user_id = $_SESSION['mallUserId'];

            //car业务逻辑
            $user_to_prod = $User->relation(true)->where("user_id=%d",array($user_id))->find();

            $i = 0;
            $judgeJump = 0;

            foreach ($user_to_prod['user_to_prod'] as $v) {
                $cou = M('prod_user')->where("user_id=%d and pid=%d",array($user_id,$v['id']))->select();


                if ($judgeJump>0 && count($cou)>1) {
                    $judgeJump --;
                    continue;
                }


                if (count($cou)>1) {
                    foreach ($cou as $k=>$v) {
                        $user_to_prod['user_to_prod']["$i"]['count'] = $cou["$k"]['count'];
                        $user_to_prod['user_to_prod']["$i"]['unit'] = $cou["$k"]['price'];
                        $user_to_prod['user_to_prod']["$i"]['content'] = $cou["$k"]['content'];
                        $user_to_prod['user_to_prod']["$i"]['color'] = $cou["$k"]['color'];
                        $user_to_prod['user_to_prod']["$i"]['price'] = (int)$cou["$k"]['price']*(int)$cou["$k"]['count'];
                        $user_to_prod['user_to_prod']["$i"]['oldId'] = $cou["$k"]['id'];

                        // $user_to_prod['user_to_prod']["$i"]['checkout'] = $cou["$user_id"]['checkout'];
                        $allPrice += $user_to_prod['user_to_prod']["$i"]['price'];
                        $i++;
                    }
                    $judgeJump = count($cou);
                    continue;
                }else{
                    $user_to_prod['user_to_prod']["$i"]['count'] = $cou['0']['count'];
                    $user_to_prod['user_to_prod']["$i"]['unit'] = $cou['0']['price'];
                    // $user_to_prod['user_to_prod']["$i"]['checkout'] = $cou["$user_id"]['checkout'];
                    $user_to_prod['user_to_prod']["$i"]['content'] = $cou['0']['content'];
                    $user_to_prod['user_to_prod']["$i"]['color'] = $cou['0']['color'];
                    $user_to_prod['user_to_prod']["$i"]['price'] = (int)$cou['0']['price']*(int)$cou['0']['count'];
                    $user_to_prod['user_to_prod']["$i"]['oldId'] = $cou['0']['id'];


                    $allPrice += $user_to_prod['user_to_prod']["$i"]['price'];
                    $i++;
                }

            }

            //总数量
            foreach ($user_to_prod['user_to_prod'] as $v) {
                $allCount += $v['count'];
            }

            $this->assign('car',$user_to_prod['user_to_prod']);
            //endcar业务逻辑


            //用户vs商品more_to_more
            $user_to_prod = $User->relation(true)->where("user_id=%d",array($user_id))->find();
            //查询该用户所购买的商品!
            // test($user_to_prod['user_to_prod']);
            $count = count($user_to_prod);// 查询满足要求的总记录数
            $Page = new \Extend\Page($count,3);
            // 实例化分页类 传入总记录数和每页显示的记录数(3)
            $show = $Page->show();// 分页显示输出
            //单独查一次count,未尝试优化
            foreach ($user_to_prod['user_to_prod'] as $k=>$v) {
                $cou = M('prod_user')->where("user_id=%d and pid=%d",array($user_id,$v['id']))->field('count')->select();

                // test($cou);
                $user_to_prod['user_to_prod']["$k"]['count'] = $cou['0']['count'];
                $user_to_prod['user_to_prod']["$k"]['price'] *=$cou['0']['count'];
                // $user_to_prod['user_to_prod']["$k"]['checkout'] = $cou["$user_id"]['checkout'];
                $allPrice += $user_to_prod['user_to_prod']["$k"]['price'];
                //价格为总价 不是单价s
            }
            // test($user_to_prod['user_to_prod']);

            /**
            收货地址
             */
            $this->proord = M('proorder')->select();

            $res = ['model' => $user_to_prod['user_to_prod'], 'allCount' => $allCount, 'allPrice' => $allPrice, 'page' => $show];
            return $res;
		}

		public function showCal(){
			$carInfo = $this->getCarInfo();
	        //遍历userinfo输出收货地址
	        $this->userinfo = M('userinfo')->select();
	        $this->assign('model', $carInfo['model']);
	        $this->assign('allCount',$carInfo['allCount']);
	        $this->assign('allPrice',$carInfo['allPrice']);
	        $this->assign('page',$carInfo['page']);
			$this->display();
		}

		public function delete_car(){
			if (I('get.action') == 'ajax') {
				if ($judge = M('prod_user')->where("id=%d",I('oldId'))->delete()) {
					$arr['success']=1;
					echo json_encode($arr);
				}else{
					$arr['success']=-0;
					echo json_encode($arr);
				}

			}
		}

		public function pro_order(){
			/**
			 不加就乱码了
			 */
			header("Content-Type:text/html;charset=utf-8");
			if (I('get.action') == 'ajax') {
				$db = M('proorder');
				/**
				 	处理三级联动
				 */
				$provinces = I('provinces');
				$city = I('city');
				$area = I('area');
				$pro_exp = explode(',',$provinces);

				$cit_exp = explode(',',$city);

				$are_exp = explode(',',$area);
				$data = array(
					'name' => I('name'),
					'tel' => I('tel'),
					'provinces' => $pro_exp['0'],
					'city' => $cit_exp['0'],
					'area' => $are_exp['0'],
					'address' => I('address'),
					'zip' => I('zip'),
					);
				if ($judge = $db->data($data)->add()) {
					$data['success']=1;
					echo json_encode($data);
				}
			}
		}

		public function settlement(){
            $carInfo = $this->getCarInfo();
            $this->userinfo = M('userinfo')->select();
            $this->assign('model', $carInfo['model']);
            $this->assign('allCount',$carInfo['allCount']);
            $this->assign('allPrice',$carInfo['allPrice']);
            $this->assign('page',$carInfo['page']);
            if ($_POST){
            	$data = $_POST;
				if($res = $this->getCheckoutInfo($carInfo['model'])){
                    $this->success('评价成功 ！',U('Index/index'));
				}else{
					$this->error('评价失败！');
				}
			}else{
                $this->display();
            }
        }

        //顺带入库
        public function getCheckoutInfo($data)
		{
			$res = [];
			foreach($data as $k => $v){
                $res[$k]['user_id'] = $_SESSION['user_id'];
                $res[$k]['pid'] = $v['id'];
				$res[$k]['count'] = $v['count'];
				$res[$k]['time'] = date('Y-m-d H:i:s',time());
				$res[$k]['price'] = intval(floatval($v['price1']) * floatval($v['count']));
                if (!$judge = M('checkout')->data($res[$k])->add()){
                    return false;
                }
			}
			return true;
		}
	}
 ?>
